﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Chronos;
public class Mage_Orb : BaseBehaviour
{
    public EntityBase Player;
    public float rotateSpeed = 3;
    public float followSpeed = 0.5f;
    public Vector2 pivotVector = new Vector2(0, 1);

    public GameObject orb;

    public int orbCount = 1;
    //public Vector2[] orbPos = new Vector2[10];
    public Dictionary<int, GameObject> orbPos = new Dictionary<int, GameObject>();
    //public Rigidbody2D rb_1;
    public void Awake()
    {
        orbCount = 1;
        Init(orbCount);

        if (Player == null)
        {
            try
            {
                Player = GameObject.FindGameObjectWithTag("Player").GetComponent<EntityBase>();
            }
            catch
            {
                Debug.Log("first init orb");
            }

        }
    }
    public void Update()
    {
        //if (Player == null)
        //{
        //    Player = GameObject.FindGameObjectWithTag("Player").GetComponent<EntityBase>();
        //}
        FollowPlayer();
        transform.RotateAround(transform.position, new Vector3(0, 0, 1), rotateSpeed);
        test();
        //Debug.Log(orbPos[1]);
    }

    public void FollowPlayer()
    {
        var distance = Player.transform.position - transform.position;
        transform.position += distance * followSpeed;
        //transform.position = Player.transform.position;
    }
    public void Init(int orbCount)
    {
        orbPos.Clear();
        transform.eulerAngles = Vector3.zero;
        for(int j = 0; j < transform.childCount; j++)
        {
            Destroy(transform.GetChild(j).gameObject);
        }
        var degree = 360 / orbCount;
        for(int i = 1; i <= orbCount; i++)
        {
            var pos = Rotate(pivotVector, degree * i);
            var _orb = Instantiate(orb, transform);
            _orb.transform.localPosition = pos;
            orbPos.Add(i, _orb);
        }
    }
    public static Vector2 Rotate(Vector2 vector, float angle)
    {
        float rad = angle * Mathf.PI / 180;
        float x = Mathf.Cos(rad);
        float y = Mathf.Sin(rad);
        return new Vector2(vector.x * x - vector.y * y, vector.x * y + vector.y * x);
    }
    public void test()
    {
        if(Input.GetKeyDown(KeyCode.J))
        {
            orbCount++;
            Init(orbCount);
        }
        if (Input.GetKeyDown(KeyCode.K))
        {
            orbCount--;
            Init(orbCount);

        }
    }

}
